﻿//Author:Michal Sporna
//License: https://operationsneakpeek.codeplex.com/license

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Media;
using System.IO;
using System.Xml.Linq;

namespace OperationSneakPeek
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        #region private fields
        private GraphicsDeviceManager graphics;
        private SpriteBatch spriteBatch;
        private GestureSample gesture;
        //private GestureSample _AvatarMovementGesture;
        private Vector2 tapPos;
        private Double _SavedTime;
     

        //private TouchCollection _Touches;
        private string _DebugOutput=string.Empty;

        #region helpers
        private double _SplashScreenTimeStart;
        private bool _SplashScreenTimeStartSet;
        
        

        #endregion


        #region used in fps counter
        private int _Fps;
        private float _ElapsedTime;
        private int _TotalFrames;
        #endregion

        //private Accelerometer accelerometer;
        #endregion

        public Game1()
        {
            try
            {
                graphics = new GraphicsDeviceManager(this);
                Content.RootDirectory = "Content";
              
                // Frame rate is 30 fps by default for Windows Phone.
                TargetElapsedTime = TimeSpan.FromTicks(333333);
                //TargetElapsedTime = TimeSpan.FromSeconds(1 / 30.0);

                // Extend battery life under lock.
                InactiveSleepTime = TimeSpan.FromSeconds(1);

                TouchPanel.EnabledGestures = GestureType.HorizontalDrag| GestureType.Tap | GestureType.DoubleTap | GestureType.Hold | GestureType.DragComplete;

               
                                //***********/TEMP


                Window.Title = "Operation Sneak Peek";
                graphics.PreferredBackBufferWidth = 800;
                graphics.PreferredBackBufferHeight = 480;
                graphics.IsFullScreen = true;
                graphics.ApplyChanges();
               


                #region Accelerometer
                //if (!Accelerometer.IsSupported)
                //{
                //    // The device on which the application is running does not support
                //    // the accelerometer sensor. Alert the user and disable the
                //    // Start and Stop buttons.
                //    //do something!
                //    try
                //    {
                //        throw new Exception("ACCELEROMETER NOT SUPPORTED, BITCH");
                //    }
                //    catch (Exception ex)
                //    {
                //        Util.ErrorLogging.LogError(ex);
                //        return;
                //    }
                //}
                //else
                //{
                //    //new instance of accelerometer
                //    if (accelerometer == null)
                //    {
                //        accelerometer = new Accelerometer();
                //        accelerometer.CurrentValueChanged += new EventHandler<SensorReadingEventArgs<AccelerometerReading>>(accelerometer_CurrentValueChanged);
                //        accelerometer.Start();
                //    }
                //}
                #endregion
            }
            catch (Exception ex)
            {
                Util.ErrorLogging.LogError(ex);
                return;
            }
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            try
            {
              
                //set current screen
                Util.Cache.CurrentScreen = Util.Cache.Screen.SplashScreen1;
                //set previous screen
                Util.Cache.PreviousScreen = Util.Cache.Screen.None;


                #region reset bools
                //set icon highlights to false
                World.WorldManager.ActionIconHighlighted = false;

                #endregion

                //start time
                World.WorldManager.MinutesLeft = 10;
                World.WorldManager.SecondsLeft = 34;
                World.WorldManager.EverythingLoaded = false;
                World.WorldManager.Inventory = new List<Util.Classes.InventoryItem>();//inventory


                //base.TargetElapsedTime = new TimeSpan(166666);
                //base.IsFixedTimeStep = false;

                base.Initialize();
            }
            catch (Exception ex)
            {
                Util.ErrorLogging.LogError(ex);
                return;
            }
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            try
            {
                // Create a new SpriteBatch, which can be used to draw textures.
                spriteBatch = new SpriteBatch(GraphicsDevice);

                // TODO: use this.Content to load your game content here

                //assign graphics manager and sprite batch to cache
                Util.Cache.spriteBatch = this.spriteBatch;
                Util.Cache.spriteBatch.Tag = false; //if true-Begin() has been called, if fase no.
                Util.Cache.graphics = this.graphics;
                Util.Cache.GraphicsDevice = this.GraphicsDevice;
                Util.Cache.ContManager = this.Content;

                
                
                //get all maps from xml files and load them
                //World.WorldManager.InitAllMaps();

               //load global content
                World.WorldManager.LoadGlobalContent();


            }
            catch (Exception ex)
            {
                Util.ErrorLogging.LogError(ex);
                return;
            }
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
            this.Content.Unload();
            
            //Util.Cache.Textures = null;
            //Util.Cache.Fonts = null;
            //Levels.LevelManager.CurrentMap = null;
            //World.WorldManager.UnloadContent();
            //Levels.LevelManager.AvailableMaps = null;
            //Util.Cache.Avatar = null;
            //Util.Cache.spriteBatch.End();
            //Util.Cache.spriteBatch.Dispose();
            //World.WorldManager.Nodes = null;
            

        }

        #region misc

        /// <summary>
        /// display current build version
        /// </summary>
        /// <returns></returns>
        private string GetVersionNumber()
        {
            //declare
            string VersionNumber=string.Empty;

            try
            {
                var CurrentAssembly = System.Reflection.Assembly.GetExecutingAssembly();
                VersionNumber = "Version:" + CurrentAssembly.ToString().Split('=')[1].Split(',')[0];

                return VersionNumber;
            }
            catch (Exception ex)
            {
                Util.ErrorLogging.LogError(ex);
                return string.Empty;
            }
        }

        #endregion


        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            //declare
            bool LastMessageBoxShown = false;

            try
            {
                //this.TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 16);  

                //assign game time to cache game time
                Util.Cache.GameTime = gameTime;
                
                
                // Allows the game to exit or go back to the previous screen
                if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                {
                    //return to previous screen
                    //Util.Cache.SetCurrentScreen(Util.Cache.PreviousScreen);

                    //if current screen is splash screen, and
                    //back button is pressed
                    //then go back
                    if (Util.Cache.CurrentScreen == Util.Cache.Screen.Game)
                    {

                        World.WorldManager.PauseON = true;
                        Util.Cache.SetCurrentScreen(Util.Cache.Screen.Pause);

                        //clear the gesture
                        gesture = new GestureSample();

                        //this.Exit();
                        return;
                    }
                }

                //home button pressed>?
                if (GamePad.GetState(PlayerIndex.One).Buttons.BigButton== ButtonState.Pressed)
                {
                    this.Exit();
                }


                #region fps counter
                _ElapsedTime += (float)gameTime.ElapsedGameTime.TotalMilliseconds;

                if (_ElapsedTime > 1000)
                {
                    _Fps = _TotalFrames;
                    _TotalFrames = 0;
                    _ElapsedTime = 0;
                }

                #endregion

              

                #region user's input

                switch (Util.Cache.CurrentScreen)
                {
                        #region Screen:GAME

                    case Util.Cache.Screen.Game:
                        {
                            ////if avatar not ready yet,
                            ////then return
                            if (Util.Cache.Avatar == null)
                            {
                                return;
                            }

                            #region prepare nodes

                            if (World.WorldManager.Nodes == null)
                            {
                                World.WorldManager.Nodes = World.PathFinding.InitNodesWithReturn();

                                ////position letters
                                //Levels.LevelManager.CurrentMap.ChosenSecretWord.PositionLetters();
                                Levels.LevelManager.CurrentMap.ChosenSecretWord.SetLetters();

                                //inform that this is work in progress demo
                                Util.MessageBox.ShowMessage("This is a demo of 'Operation Sneak Peek'. Please note this is still work in progress-missing multiple features,art,cutscenes,audio,QA,level design...Please try the core gameplay and enjoy:)");

                            }

                            #endregion

                            
                            #region read gesture

                            while (TouchPanel.IsGestureAvailable)
                            {
                                //read the gesture
                                gesture = TouchPanel.ReadGesture();
                                //get position
                                tapPos = gesture.Position;

                                if (gesture.GestureType == GestureType.Tap)
                                {
                                    //this can be done only if not choosing nodes 
                                    //do not want situation, when node covers the bomb, player taps on node (selects it) and bomb under it is activated
                                    if (!World.ScannerManager.ChoosingNodes && !World.MapScanner.IsShown)
                                    {
                                        //NEED TO KNOW NOW,BECAUSE IT IS VERY IMPORANT AS NO OTHER ELEMENTS ARE VISIBLE WHILE DEFUSING THE BOMB
                                        World.WorldManager.IsAvatarDefusingBomb(new Vector2(tapPos.X, tapPos.Y));
                                    }
                                }
                                


                                
                            }

                         

                            #endregion

                            //if bomb is being defused, avatar, npc are not being updated
                            if (!World.WorldManager.IsDefusingBomb)
                            {


                                //show message box
                                #region MESSAGE BOX
                                //message box is currently shown
                                //do nothing until the message box is closed
                                if (Util.MessageBox.ShowMessageBox && World.WorldManager.PauseON)
                                {
                                    if (gesture.GestureType == GestureType.Tap)
                                    {
                                        if (Util.MessageBox.IsLastMessageBox)
                                        {
                                            LastMessageBoxShown = true;
                                        }

                                        Util.MessageBox.OnOKButtonClicked(tapPos);
                                        //reset gesture so no other operation is done
                                        gesture = new GestureSample();

                                        if (LastMessageBoxShown)
                                        {
                                            //World.WorldManager.UnloadContentAndLoadGlobals();
                                            World.WorldManager.ClearGameWorld();
                                            World.WorldManager.LoadGameConfig();
                                            Util.Cache.SetCurrentScreen(Util.Cache.Screen.Menu);
                                        }
                                        

                                        return;
                                    }
                                }
                                #endregion


                                #region npc movement

                                //npcs movement (only if pause is turned off)
                                if (!World.WorldManager.PauseON && !World.MapScanner.IsShown)
                                {

                                    #region item throw in progress
                                    //if throw complete then 
                                    //distraction will take place
                                    //it must be done before the npc moves as distraction() modifies current move pattern and current FOV
                                    World.WorldManager.MakeProgressInThrow();

                                    #endregion

                                    if (Levels.LevelManager.CurrentMap.CurrentMapCell.NPCs != null && Levels.LevelManager.CurrentMap.CurrentMapCell.NPCs.Count > 0)
                                    {
                                        for (int npcI = 0; npcI < Levels.LevelManager.CurrentMap.CurrentMapCell.NPCs.Count; npcI++)
                                        {
                                            if (World.WorldManager.IsHeatActive)
                                            {
                                                //if heat is active move only npc that caused the heat
                                                if (Levels.LevelManager.CurrentMap.CurrentMapCell.NPCs[npcI].HeatDrawn)
                                                {
                                                    Levels.LevelManager.CurrentMap.CurrentMapCell.NPCs[npcI].MoveNPC();
                                                }

                                            }
                                            else
                                            {
                                                //draw npc distraction control (if player in throwing mode)
                                                Levels.LevelManager.CurrentMap.CurrentMapCell.NPCs[npcI].PrepareDistractionControl();

                                                Levels.LevelManager.CurrentMap.CurrentMapCell.NPCs[npcI].MoveNPC();
                                            }

                                        }
                                    }
                                }

                                #endregion //and distraction control

                                //HOLD GESTURE??
                                //SCANNING?

                               
                                    #region HOLD GESTURE?


                                    //NEW HOLD
                                    #region HOLD

                                    TouchCollection touches = TouchPanel.GetState();


                                    foreach (TouchLocation touch in touches)
                                    {

                                        //save hold start time
                                        if ((touch.State == TouchLocationState.Pressed))
                                        {
                                            //save time
                                            _SavedTime = Util.Cache.GameTime.TotalGameTime.TotalMilliseconds;
                                        }

                                        //if holding:
                                        if (touch.State == TouchLocationState.Moved)
                                        {


                                            if (Util.Cache.GameTime.TotalGameTime.TotalMilliseconds - _SavedTime > 1000)
                                            {
                                                if (World.ScannerManager.IsScanning)
                                                {
                                                    //continue scanning
                                                    World.ScannerManager.Scan();
                                                    _SavedTime = Util.Cache.GameTime.TotalGameTime.TotalMilliseconds;


                                                }
                                                else
                                                {
                                                    //start scanning
                                                    if (!World.ScannerManager.StartScanning(tapPos))
                                                    {
                                                        World.ScannerManager.EndScanningProcess();
                                                        _SavedTime = Util.Cache.GameTime.TotalGameTime.TotalMilliseconds;


                                                    }
                                                }

                                                break;
                                            }
                                        }
                                        else
                                        {
                                            World.ScannerManager.EndScanningProcess();

                                        }



                                    }

                                    #endregion

                                    #endregion
                                


                             
                                if (!World.ScannerManager.IsScanning)
                                {
                                    

                                    #region DOUBLE TAP

                                    //see if avatar action menu should be closed
                                    //already (it happens after x seconds)
                                    //World.WorldManager.IsAvatarActionMenuNeededToBeClosed(); //REPLACE 


                                    if (gesture.GestureType == GestureType.DoubleTap)
                                    {
                                        if (World.MapScanner.IsShown)
                                        {
                                            #region CLOSE SCANNER MAP
                                            //close map scanner if is opened and player double tapped on it
                                            World.MapScanner.CloseScannerMap();

                                            #endregion
                                        }
                                        else
                                        {
                                            #region OPEN INVENTORY


                                            if ((tapPos.X > Util.Cache.Avatar.CurrentPosition.X && tapPos.X < (Util.Cache.Avatar.CurrentPosition.X + Util.Cache.Avatar.Width)) && (tapPos.Y > Util.Cache.Avatar.CurrentPosition.Y && tapPos.Y < (Util.Cache.Avatar.CurrentPosition.Y + Util.Cache.Avatar.Height)))
                                            {
                                                //action icon
                                                //highlight if not highligted
                                                if (World.WorldManager.IsAvatarActionMenuOpen)
                                                {
                                                    World.WorldManager.IsAvatarActionMenuOpen = false;
                                                    //pause off
                                                    World.WorldManager.PauseON = false;

                                                    //reset slot positions
                                                    World.WorldManager.OddSlotPos = new Vector2(0, 0);
                                                    World.WorldManager.EvenSlotPos = new Vector2(0, 0);
                                                    //disapose of inventory slots collection
                                                    World.WorldManager.InventorySlots = null;

                                                }
                                                else
                                                {
                                                    //open the inventory
                                                    //only if player not in throwing mode 
                                                    if (!Util.Cache.Avatar.ThrowDirectionArrowsDrawn)
                                                    {

                                                        World.WorldManager.IsAvatarActionMenuOpen = true;
                                                        //pause on
                                                        World.WorldManager.PauseON = true;
                                                        //save elapsed time for inactivity
                                                        World.WorldManager.ElapsedMs1 = Util.Cache.GameTime.ElapsedGameTime.TotalMilliseconds;

                                                        //set initial slot positions
                                                        //World.WorldManager.OddSlotPos = new Vector2((Util.Cache.GraphicsDevice.Viewport.Width / 2) - World.WorldManager.WorldConfig.InventorySlotWidth / 2, (Util.Cache.GraphicsDevice.Viewport.Height / 2) - World.WorldManager.WorldConfig.InventorySlotHeight / 2);
                                                        //World.WorldManager.WorldConfig.InventorySlotWidth/3 [SPACE BETWEEN SLOTS]
                                                        //World.WorldManager.EvenSlotPos = new Vector2(((Util.Cache.GraphicsDevice.Viewport.Width / 2) - World.WorldManager.WorldConfig.InventorySlotWidth / 2) - World.WorldManager.WorldConfig.InventorySlotWidth - (World.WorldManager.WorldConfig.InventorySlotWidth / 3), (Util.Cache.GraphicsDevice.Viewport.Height / 2) - World.WorldManager.WorldConfig.InventorySlotHeight / 2);

                                                        World.WorldManager.OddSlotPos = new Vector2(((Util.Cache.GraphicsDevice.Viewport.Width / 2) - World.WorldManager.WorldConfig.InventorySlotWidth / 2) - World.WorldManager.WorldConfig.InventorySlotWidth - (World.WorldManager.WorldConfig.InventorySlotWidth / 3), (Util.Cache.GraphicsDevice.Viewport.Height / 2) - World.WorldManager.WorldConfig.InventorySlotHeight);
                                                        //World.WorldManager.WorldConfig.InventorySlotWidth/3 [SPACE BETWEEN SLOTS] 
                                                        World.WorldManager.EvenSlotPos = new Vector2((Util.Cache.GraphicsDevice.Viewport.Width / 2) - World.WorldManager.WorldConfig.InventorySlotWidth / 2, (Util.Cache.GraphicsDevice.Viewport.Height / 2) - World.WorldManager.WorldConfig.InventorySlotHeight);

                                                        //prepare inventory
                                                        World.WorldManager.PrepareInventory();

                                                        //if (Util.Cache.Avatar.IsMoving)
                                                        //{
                                                        //    //end following
                                                        //    Util.Cache.Avatar.EndFollowing();
                                                        //}

                                                    }
                                                }
                                            }

                                            

                                            #endregion
                                        }

                                    
                                    }

                                    #endregion

                                    #region PLAYER TAPPED ON THE SCREEN

                                    //determine what has been tapped
                                    if (gesture.GestureType == GestureType.Tap)
                                    {

                                        // player selected a node to be scanned
                                        if (!World.ScannerManager.SelectNodeToScan(tapPos))
                                        {

                                            #region SCANNER MAP
                                            if (!World.MapScanner.MarkNode(new int[] { (int)tapPos.X, (int)tapPos.Y }))
                                            {
                                                World.MapScanner.ContextMenuItemClicked(new int[] { (int)tapPos.X, (int)tapPos.Y });
                                            }


                                            #endregion


                                            //if scanner map is not shown, do everything below. If 
                                            //map scanner shown, do not use items from inentory, move avatar, or perfom any other action
                                            if (!World.MapScanner.IsShown)
                                            {

                                                //player tapped on a node to be scanned, so do not perform any other operation
                                                //if player tapped outside the scanner node, then proceed normally (selectNodeToScan=false)


                                                #region using items from inventory
                                                //method needed here
                                                //use an item if tapped on item
                                                World.WorldManager.UseItemFromInventory(new Vector2(tapPos.X, tapPos.Y));



                                                #endregion


                                                //do other actions only if inventory is closed completely
                                                //sometimes at the time of click outside inventory slot, inventory was being closed but tap was registered as well and avatar
                                                //started to move
                                                if (World.WorldManager.InventoryClosed)
                                                {

                                                    #region player is throwing an object
                                                    //check if throw direction arrow was clicked, if yes then draw throw field of reach
                                                    Util.Cache.Avatar.PressThrowDirectionArrow(tapPos);
                                                    //make a throw?:
                                                    World.WorldManager.MakeAThrow(tapPos);

                                                    #endregion

                                                    #region obstacle interaction button
                                                    //reset the flag
                                                    World.WorldManager.ObstacleInteractionButtonPressed = false;

                                                    //loop thru all obstacles to draw, and see if a interact button for one of them was clicked
                                                    for (int oi = 0; oi < Levels.LevelManager.CurrentMap.CurrentMapCell.Obstacles.Count; oi++)
                                                    {
                                                        //only if this obstacle is interactive
                                                        if (Levels.LevelManager.CurrentMap.CurrentMapCell.Obstacles[oi].Interactive)
                                                        {
                                                            if (Levels.LevelManager.CurrentMap.CurrentMapCell.Obstacles[oi].ToolIcon.DoSomethingIfPressed(tapPos, Levels.LevelManager.CurrentMap.CurrentMapCell.Obstacles[oi]))
                                                            {
                                                                break;
                                                            }
                                                        }
                                                    }


                                                    #endregion



                                                    #region MOVEMENT

                                                    //can't move if pause is on
                                                    if (!World.WorldManager.PauseON && !World.WorldManager.UsingItem && !World.WorldManager.IsAvatarActionMenuOpen && !Util.Cache.Avatar.ThrowDirectionArrowsDrawn && !World.WorldManager.ThrowFieldOfReachReady && !World.WorldManager.ObstacleInteractionButtonPressed)
                                                    {

                                                        #region movement

                                                        if (Util.Cache.Avatar.IsFollowing)
                                                        {

                                                            if (!Util.Cache.Avatar.IsTapOnMe(new int[] { (int)tapPos.X, (int)tapPos.Y }))
                                                            {


                                                                #region search when avatar is moving

                                                                if (Util.Cache.Avatar.MovePoints != null && Util.Cache.Avatar.TargetMoveCheckpoint != null && Util.Cache.Avatar.CurrentMoveCheckpoint != null)
                                                                {

                                                                    //indicate the movement start
                                                                    World.PathFinding.StartPathFinding = true;

                                                                    ////init the path following process
                                                                    //World.PathFinding.InitNodes();
                                                                    //start looking for the path
                                                                    if (World.PathFinding.StartSearching(Util.Cache.Avatar.TargetMoveCheckpoint.Pos, new Vector2(gesture.Position.X, gesture.Position.Y)))
                                                                    {

                                                                        //if true, then the path has been found
                                                                        World.PathFinding.StartPathFinding = false; //path has been found
                                                                        //start movign
                                                                        Util.Cache.Avatar.IsMoving = true;

                                                                    }
                                                                    else
                                                                    {
                                                                        //World.PathFinding.EndPathFinding(); //YOU CAN COMMENT THIS LINE TO DEBUG DRAW THE NODES
                                                                        Util.Cache.Avatar.IsMoving = false;
                                                                        World.PathFinding.StartPathFinding = false; //path has been found

                                                                    }
                                                                }

                                                                #endregion


                                                            }

                                                        }
                                                        else
                                                        {

                                                            #region Regular serach (avatar is standing)

                                                            //indicate the movement start
                                                            World.PathFinding.StartPathFinding = true;


                                                            //init the path following process
                                                            //World.PathFinding.InitNodes();
                                                            //start looking for the path
                                                            if (World.PathFinding.StartSearching(new Vector2(gesture.Position.X, gesture.Position.Y)))
                                                            {

                                                                //if true, then the path has been found
                                                                World.PathFinding.StartPathFinding = false; //path has been found
                                                                //start movign
                                                                Util.Cache.Avatar.IsMoving = true;

                                                            }
                                                            else
                                                            {
                                                                //World.PathFinding.EndPathFinding(); //YOU CAN COMMENT THIS LINE TO DEBUG DRAW THE NODES
                                                                Util.Cache.Avatar.IsMoving = false;
                                                                World.PathFinding.StartPathFinding = false; //path has been found

                                                            }

                                                            #endregion

                                                        }

                                                        #endregion //MOVEMENT


                                                    }






                                                    //#region start moving CHANGE: IF PLAYER TAPPED OUTSIDE THE THROW FIELD OF REACH,THEN CANCEL THROWING-or is it implemented already? 1.16
                                                    //if (!World.WorldManager.PauseON && !World.WorldManager.IsAvatarActionMenuOpen && !Util.Cache.Avatar.ThrowDirectionArrowsDrawn)
                                                    //{
                                                    //    //move pattern drawing has been ended
                                                    //    //start walking
                                                    //    Util.Cache.Avatar.FollowMovePattern();

                                                    //    //exit throwing mode, if throw complete
                                                    //    if (Util.Cache.Avatar.DrawingMovePatternEnd)
                                                    //    {
                                                    //        //end throwing mode, if active
                                                    //        if (!World.WorldManager.ThrowComplete)
                                                    //        {
                                                    //            World.WorldManager.ExitThrowingMode();
                                                    //        }


                                                    //    }
                                                    //}
                                                    //#endregion

                                                    //this: before move
                                                    ////walk animation
                                                    //Util.Cache.Avatar.AnimationTimer += (float)gameTime.ElapsedGameTime.Milliseconds;

                                                    //this in the move
                                                    //if (Util.Cache.Avatar.AnimationTimer > Util.Cache.Avatar.AnimatingInterval)
                                                    //{


                                                    //}

                                                    //this after move
                                                    //increment animation inverval
                                                    //Util.Cache.Avatar.ControlWalkAnimation();


                                                    #endregion
                                                }
                                            }//if map scanner is shown
                                        }//if is choosing node mode
                                     
                                    }//if tapped

                                    #endregion

                                    #region START MOVING

                                    if (Util.Cache.Avatar.IsMoving && !World.WorldManager.PauseON && !World.MapScanner.IsShown)//is moving should be made false as soon as obstacle/target has been reached
                                    {
                                        //move
                                        Util.Cache.Avatar.FollowMovePattern();
                                    }
                                    #endregion

                                } //if is scanning


                                #region refill battery level
                                World.ScannerManager.RefillBattery();
                                #endregion

                                //#region update breathing bar if necessary

                                //if (Util.Cache.Avatar.Position == Util.Helpers.PublicEnums.AvatarPosition.Dive)
                                //{
                                //    //avatar is diving
                                //    World.WorldManager.SetBreathingBars();

                                //}
                                //else
                                //{
                                //    //reset fields
                                //    World.WorldManager.BreathProgressBar1 = new Rectangle(0, 0, 0, 0);
                                //    World.WorldManager.BreathProgressBar2 = new Rectangle(0, 0, 0, 0);
                                //    World.WorldManager.CurrentTimeElapsed = -1;
                                //    World.WorldManager.BreathTimeElapsedSet = false;
                                //    World.WorldManager.BreathProgressBarWidth = -1;
                                //}


                                //#endregion

                            }//IF DEFUSING BOMB
                            else
                            {
                                #region bomb

                                //determine what has been tapped
                                if (gesture.GestureType == GestureType.Tap)
                                {

                                    //get position
                                    tapPos = gesture.Position;

                                    #region bomb defusing

                                    //if prep completed, player can be only defusing bomb now

                                    //see if player is cutting some wire...
                                    World.BombHandler.IsPlayerCuttingTheWire(new Vector2(tapPos.X, tapPos.Y));
                                    //see if player is exiting the defusing mode...
                                    World.BombHandler.IsPlayerCancelingTheDefusing(new Vector2(tapPos.X, tapPos.Y));

                                    #endregion



                                }

                                #region processing bomb

                                #region wire shuffling

                                if (World.WorldManager.IsDefusingBomb && World.BombHandler.StartShuffle && !World.BombHandler.ShuffleDone)
                                {
                                    
                                       
                                            //see if start shuffling
                                            if (Util.Cache.GameTime.TotalGameTime.TotalMilliseconds - World.BombHandler.TimeElapsedSinceWiresDrawn > World.WorldManager.BombInstanceBeingDefused.Shuffle.ShufflePeriod)
                                            {
                                                //start covering wires 
                                                World.BombHandler.CoverWires = true;
                                                World.BombHandler.Shuffle();

                                            }
                                        
                                    



                                }

                                #endregion

                                #region bomb failed information

                                if (World.BombHandler.ShowingBombFailInformation)
                                {
                                    //increment alpha ratio
                                    World.BombHandler.BombFailedInformationAlphaRatio += World.BombHandler.BombFailedInformationAlphaIncrementor;


                                }


                                #endregion

                                #endregion

                                #endregion



                            }

                            #region awarding points and showing sliding info

                            if (World.WorldManager.AwardingAnimationOn)
                            {
                                //increment flying points step only if points are not in the middle of the screen yet


                                if ((World.WorldManager.AcheivementStringStep + (Util.Cache.GetFont("HUDScore").FontFace.MeasureString(World.WorldManager.AcheivementInfo).Length() / 2) < (float)Util.Cache.GraphicsDevice.Viewport.Width / 2) && (World.WorldManager.PointsStringStep + (Util.Cache.GetFont("HUDScore").FontFace.MeasureString(World.WorldManager.AcheivementPoints).Length() / 2) > (float)Util.Cache.GraphicsDevice.Viewport.Width / 2))
                                {
                                    World.WorldManager.AcheivementStringStep += 13;
                                    World.WorldManager.PointsStringStep -= 19;
                                }
                                else
                                {
                                    //start dissolving points that flew to the center of the screen
                                    World.WorldManager.AwardPointsAlphaValue += World.WorldManager.AlphaIncrementor;

                                    //add points if this is not slidiging in info but awarding points
                                    if (!World.WorldManager.SlidingInInformation)
                                    {
                                        if (World.WorldManager.AwardPointsAlphaValue >= 1)
                                        {

                                            //set points added to true (if not true aleready)
                                            //points will glow for a second indicating that they were added
                                            if (!World.WorldManager.PointsAdded && !World.WorldManager.DoNotAddPoints)
                                            {
                                                World.WorldManager.PointsGlowTimer = Util.Cache.GameTime.TotalGameTime.TotalMilliseconds;
                                                World.WorldManager.PointsAdded = true;
                                            }

                                          

                                            //and then stop drawing it at all
                                            World.WorldManager.AwardingAnimationOn = false;

                                            if (World.WorldManager.DoNotAddPoints)
                                            {
                                                World.WorldManager.AcheivementInfo = null;
                                                World.WorldManager.PointsAdded = false;

                                            }

                                        }
                                    }
                                }

                            }
                            else
                            {
                                //animation is off

                                //set current miliseconds elapsed
                                if (World.WorldManager.AcheivementInfo != null) //if acheivement info is null, it means that achievement has been awarded moments ago. Otherwise no achievement,do not glow the points.
                                {
                                    if (!World.WorldManager.SlidingInInformation)
                                    {
                                        if (World.WorldManager.PointsAdded) //points being added?
                                        {
                                            //points are already glowin, then see if it's time to stop this 
                                            //adding points
                                            if (World.WorldManager.PointsBeforeAwarding + World.WorldManager.PointsToAdd == Levels.LevelManager.CurrentMap.Points)
                                            {

                                                World.WorldManager.PointsToAdd = 0;

                                                //reset strings and fields
                                                World.WorldManager.AcheivementInfo = null;
                                                World.WorldManager.AcheivementPoints = null;
                                                World.WorldManager.AcheivementStringStep = 0;
                                                World.WorldManager.AwardPointsAlphaValue = 0;
                                                World.WorldManager.PointsStringStep = 0;
                                                World.WorldManager.PointsGlowTimer = 0;
                                                //meaning points being added, if false, then display regular hud
                                                World.WorldManager.PointsAdded = false;
                                                World.WorldManager.PointsBeforeAwarding = 0;
                                            }
                                            else
                                            {
                                                Levels.LevelManager.CurrentMap.Points += 20;
                                            }

                                        }
                                    }
                                }
                                else
                                {
                                    //reset strings and fields
                                    World.WorldManager.AcheivementInfo = null;
                                    World.WorldManager.AcheivementPoints = null;
                                    World.WorldManager.AcheivementStringStep = 0;
                                    World.WorldManager.AwardPointsAlphaValue = 0;
                                    World.WorldManager.PointsStringStep = 0;
                                    World.WorldManager.PointsGlowTimer = 0;
                                    //meaning points being added, if false, then display regular hud
                                    World.WorldManager.PointsAdded = false;
                                    World.WorldManager.PointsBeforeAwarding = 0;
                                    World.WorldManager.SlidingInInformation = false;
                                    World.WorldManager.R = -1;
                                    World.WorldManager.G = -1;
                                    World.WorldManager.B = -1;
                                    World.WorldManager.A = -1;

                                }
                            }



                            #endregion
                            #region remove items to draw , if already collected

                            Levels.LevelManager.CurrentMap.CurrentMapCell.RemoveItemToDrawFromItems();

                            #endregion

                           

                            //clear the gesture
                            gesture = new GestureSample();
                            


                            break;
                    #endregion

                        }
                    case Util.Cache.Screen.LoadingNow:
                        {

                            #region Screen: LOADING NOW


                            #endregion

                            break;
                        }
                    case Util.Cache.Screen.SplashScreen1:
                        {
                            #region Screen:SPLASH SCREEN
                            //load config
                            World.WorldManager.LoadGameConfig();
                            //Util.Cache.SetCurrentScreen(Util.Cache.Screen.Menu);

                            //and not just add another x seconds of splash screen for user to admire it...
                            if (!_SplashScreenTimeStartSet)
                            {
                                _SplashScreenTimeStart = gameTime.TotalGameTime.TotalMilliseconds;
                                _SplashScreenTimeStartSet = true;
                            }
                            else
                            {
                                //if splash screen time set, then see if x seconds have elapsed....
                                if (gameTime.TotalGameTime.TotalMilliseconds - _SplashScreenTimeStart >= 3000)
                                {
                                    //show main menu
                                    Util.Cache.SetCurrentScreen(Util.Cache.Screen.Menu);
                                }
                            }



                            #endregion



                            break;
                        }
                    case Util.Cache.Screen.MapSelector:
                        {
                            #region read gesture
                            //clear gesture
                            gesture = new GestureSample();
                            //read gesture (Except for gestures where continous pos getting is required)
                            while (TouchPanel.IsGestureAvailable)
                            {

                                tapPos = Vector2.Zero;
                                gesture = TouchPanel.ReadGesture();
                                tapPos = gesture.Position;

                            }

                            #endregion

                            #region Screen: MAP SELECTOR

                            //see what map player has chosen
                            if (gesture.GestureType == GestureType.Tap)
                            {

                                //get position
                                tapPos = gesture.Position;
                                //see what map has been chosen
                                if (Screens.MapSelector.IsMapChosen(tapPos))
                                {
                                    ////change screen to level selector
                                    //Util.Cache.SetCurrentScreen(Util.Cache.Screen.Game);

                                    //Screens.MapSelector.MapSelectorItems = null;

                                    gesture = new GestureSample();//empty gesture
                                }

                            }
                            #endregion

                            break;
                        }
                    case Util.Cache.Screen.LevelSelector:
                        {
                            //OBSCURE AS OF 06.01.2013-
                            //CURRENTLY THE MAP IS LOADED
                            //AND AVATAR CAN GO FROM 1 CELL TO ANOTHER VIA PORTALS
                            #region read gesture
                            //clear gesture
                            gesture = new GestureSample();
                            //read gesture (Except for gestures where continous pos getting is required)
                            while (TouchPanel.IsGestureAvailable)
                            {

                                tapPos = Vector2.Zero;
                                gesture = TouchPanel.ReadGesture();
                                tapPos = gesture.Position;

                            }

                            #endregion
                            #region Screen: LEVEL SELECTOR

                            if (gesture.GestureType == GestureType.Tap)
                            {

                                //get position
                                tapPos = gesture.Position;
                                //see what map has been chosen
                                if (Screens.LevelSelector.IsLevelChosen(tapPos))
                                {
                                    //change screen to game
                                    Util.Cache.SetCurrentScreen(Util.Cache.Screen.Game);

                                    Screens.LevelSelector.Items = null;
                                   
                                }

                            }

                            #endregion

                            break;
                        }
                    case Util.Cache.Screen.Menu:
                        {
                            #region read gesture
                            //clear gesture
                            gesture = new GestureSample();
                            //read gesture (Except for gestures where continous pos getting is required)
                            while (TouchPanel.IsGestureAvailable)
                            {

                                tapPos = Vector2.Zero;
                                gesture = TouchPanel.ReadGesture();
                                tapPos = gesture.Position;

                            }

                            #endregion
                            #region menu
                            if (gesture.GestureType == GestureType.Tap)
                            {
                                tapPos = gesture.Position;


                                //start game?
                                if ((tapPos.X >= 4 && tapPos.X <= 260) && (tapPos.Y >= 155 && tapPos.Y <= 265))
                                {
                                    //start game
                                    Util.Cache.SetCurrentScreen(Util.Cache.Screen.MapSelector);
                                  
                                    


                                    return;
                                }

                                ////store?
                                if ((tapPos.X >= 4 && tapPos.X <= 260) && (tapPos.Y >= 275 && tapPos.Y <= 353))
                                {
                                    //enter store
                                    Util.Cache.SetCurrentScreen(Util.Cache.Screen.Store);
                                    return;
                                }

                                ////Exit?
                                if ((tapPos.X >= 4 && tapPos.X <= 260) && (tapPos.Y >= 360 && tapPos.Y <= 420))
                                {
                                    //exit app
                                    this.Exit();
                                    return;
                                }

                            }
                            #endregion

                            break;
                        }
                    case Util.Cache.Screen.Error:
                        {
                            #region read gesture
                            //clear gesture
                            gesture = new GestureSample();
                            tapPos = Vector2.Zero;
                            //read gesture (Except for gestures where continous pos getting is required)
                            while (TouchPanel.IsGestureAvailable)
                            {

                                tapPos = Vector2.Zero;
                                gesture = TouchPanel.ReadGesture();
                                tapPos = gesture.Position;

                            }

                            #endregion
                            #region error screen

                            if (gesture.GestureType == GestureType.Tap)
                            {
                                //get location of the tap
                                tapPos = gesture.Position;

                                //if it's in a range of Close button, then close error popup
                                if (((tapPos.X > (Util.Cache.GraphicsDevice.Viewport.Width / 2) - 100) && (tapPos.X < (Util.Cache.GraphicsDevice.Viewport.Width / 2) + 50)) && (tapPos.Y > (Util.Cache.GraphicsDevice.Viewport.Height - 70)) && (tapPos.Y < (Util.Cache.GraphicsDevice.Viewport.Height + 60)))
                                {
                                    //close error popup
                                    Util.ErrorLogging.CloseExceptionPopup();

                                    //and draw other screen
                                    Util.Cache.CurrentScreen = Util.Cache.PreviousScreen;
                                }

                            }
                            #endregion

                            break;
                        }
                    case Util.Cache.Screen.GameOver:
                        {
                            #region read gesture
                            //clear gesture
                            gesture = new GestureSample();
                            tapPos = Vector2.Zero;
                            //read gesture (Except for gestures where continous pos getting is required)
                            while (TouchPanel.IsGestureAvailable)
                            {

                                tapPos = Vector2.Zero;
                                gesture = TouchPanel.ReadGesture();
                                tapPos = gesture.Position;

                            }

                            #endregion
                            #region game over

                            if (tapPos.X > 0 && tapPos.X < Util.Cache.GraphicsDevice.Viewport.Width)
                            {
                                //delete player isntance
                                Util.Cache.Avatar = null;
                                World.WorldManager.ClearGameWorld();
                                World.WorldManager.LoadGameConfig();

                                Util.Cache.SetCurrentScreen(Util.Cache.Screen.Menu);
                            }



                            #endregion

                            break;

                        }
                    case Util.Cache.Screen.Pause:
                        {
                            #region PAUSE
                            #region read gesture
                            //clear gesture
                            gesture = new GestureSample();
                            tapPos = Vector2.Zero;
                            //read gesture (Except for gestures where continous pos getting is required)
                            while (TouchPanel.IsGestureAvailable)
                            {

                                tapPos = Vector2.Zero;
                                gesture = TouchPanel.ReadGesture();
                                tapPos = gesture.Position;

                            }

                            #endregion

                            #region choosing pause option

                            if (gesture.GestureType == GestureType.Tap)
                            {
                                Screens.Pause.CheckWhichPauseOptionHasBeenChosen(new int[] { (int)tapPos.X, (int)tapPos.Y });
                                gesture = new GestureSample();
                                tapPos = Vector2.Zero;
                            }
                            #endregion

                            #endregion

                            break;
                        }
                    case Util.Cache.Screen.Store:
                        {
                            #region STORE

                            #region read gesture
                            //clear gesture
                            gesture = new GestureSample();
                            //read gesture (Except for gestures where continous pos getting is required)
                            while (TouchPanel.IsGestureAvailable)
                            {

                                tapPos = Vector2.Zero;
                                gesture = TouchPanel.ReadGesture();
                                tapPos = gesture.Position;

                            }

                            #endregion

                            Screens.Store.PressButton(new int[] { (int)tapPos.X, (int)tapPos.Y });

                            #endregion

                            break;
                        }
                    case Util.Cache.Screen.LoadMap:
                        {
                            #region LOAD MAP
                            Screens.LoadingMap.LoadMap();
                            #endregion

                            break;
                        }
                }

                #endregion



                base.Update(gameTime);
            }
            catch (Exception ex)
            {
                Util.ErrorLogging.LogError(ex);

                tapPos = Vector2.Zero;

                return;
            }
        }

        #region accelerometer event

        /// <summary>
        /// Detects when a current value of accelerometer is changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //void accelerometer_CurrentValueChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e)
        //{
        //    try
        //    {
        //        //read value from accelerometer
        //        World.WorldManager.accReading = e.SensorReading.Acceleration;

        //        if (Util.Cache.MainCharacter != null)
        //        {
        //            if (e.SensorReading.Acceleration.Y < 0)
        //            {
        //                //lean right
        //                Util.Cache.MainCharacter.CurrentState = Characters.MainCharacter.States.LeanRight1;
        //            }
        //            else
        //            {
        //                //lean back
        //                Util.Cache.MainCharacter.CurrentState = Characters.MainCharacter.States.LeanLeft;
        //            }

        //            if (e.SensorReading.Acceleration.Y == 0)
        //            {
        //                Util.Cache.MainCharacter.CurrentState = Characters.MainCharacter.States.IdleRight;
        //            }
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        Util.ErrorLogging.LogError(ex);
        //        return;
        //    }
        //}

        #endregion


        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            try
            {
                spriteBatch.Begin();

                //default back color-blue
                GraphicsDevice.Clear(Color.Blue);
                //increment total frames (used in fps counter)
                _TotalFrames++;

                //draw screen
                switch (Util.Cache.CurrentScreen)
                {
                    case Util.Cache.Screen.Game:
                        {
                            #region draw the game
                            GraphicsDevice.Clear(Color.SkyBlue);

                          

                            //draw world
                            #region WORLD
                            World.WorldManager.DrawLevel();

                         

                            #endregion

                            //do not draw avatar and npc when defusing a bomb
                            if (!World.WorldManager.IsDefusingBomb)
                            {
                                if (World.MapScanner.IsShown)
                                {
                                    World.MapScanner.DrawMapNodes();
                                    World.MapScanner.DrawContextMenu();
                                }
                                else
                                {

                                    #region UNCOVERED LETTERS
                                    ////draw only if at least 1letter is uncovered
                                    if (Levels.LevelManager.CurrentMap.LettersFound > 0)
                                    {

                                    for (int ul = 0; ul < Levels.LevelManager.CurrentMap.ChosenSecretWord.Letters.Count; ul++)
                                    {
                                        if (Levels.LevelManager.CurrentMap.ChosenSecretWord.Letters[ul].Uncovered && Levels.LevelManager.CurrentMap.CurrentMapCell.ID == Levels.LevelManager.CurrentMap.ChosenSecretWord.Letters[ul].MapCellID)
                                        {
                                            if (Levels.LevelManager.CurrentMap.ChosenSecretWord.Letters[ul].Pos != null)
                                            {
                                                Levels.LevelManager.CurrentMap.ChosenSecretWord.Letters[ul].DrawUncovered();
                                            }
                                        }
                                    }

                                    }
                                    #endregion

                                    #region AVATAR MOVE PATTERN

                                    Util.Cache.Avatar.DrawMovePattern();

                                    if (Util.Cache.Avatar.DrawingMovePatternEnd)
                                    {
                                        //mark avatar's destination
                                        Util.Cache.Avatar.DrawAvatarDestination();
                                    }

                                    #endregion

                                    #region BOMBS

                                    //draw bomb(s)
                                    for (int bombI = 0; bombI < Levels.LevelManager.CurrentMap.CurrentMapCell.Bombs.Count; bombI++)
                                    {


                                        Levels.LevelManager.CurrentMap.CurrentMapCell.Bombs[bombI].Draw();
                                    }
                                    #endregion

                                    #region LETTER/BOMB SCANNER

                                    World.ScannerManager.DrawChoosingNodesMode();
                                    World.ScannerManager.DrawLetterUncovered();
                                    World.ScannerManager.DrawBombUncovered();
                                    World.ScannerManager.DrawScanButton();
                                    World.ScannerManager.DrawScanning();
                                    World.ScannerManager.DrawBatteryBar();
                                    #endregion

                                    //draw NPCs
                                    #region NPCs
                                    if (Levels.LevelManager.CurrentMap.CurrentMapCell.NPCs != null && Levels.LevelManager.CurrentMap.CurrentMapCell.NPCs.Count > 0)
                                    {
                                        foreach (Characters.NPC npc in Levels.LevelManager.CurrentMap.CurrentMapCell.NPCs)
                                        {
                                            npc.Draw();
                                        }
                                    }
                                    #endregion

                                    #region BREATHING BARS

                                    //if (Util.Cache.Avatar.Position == Util.Helpers.PublicEnums.AvatarPosition.Dive)
                                    //{
                                    //    Util.Cache.Draw(Util.Cache.GetTexture("progressBar1").Text2D, World.WorldManager.BreathProgressBar1, Color.White);
                                    //    Util.Cache.Draw(Util.Cache.GetTexture("progressBar2").Text2D, World.WorldManager.BreathProgressBar2, Color.White);


                                    //}

                                    if (Util.Cache.Avatar.Position == Util.Helpers.PublicEnums.AvatarPosition.Dive)
                                    {
                                        //avatar is diving
                                        World.WorldManager.SetBreathingBars();

                                        //draw
                                        Util.Cache.Draw(Util.Cache.GetTexture("progressBar1").Text2D, World.WorldManager.BreathProgressBar1, Color.White);
                                        Util.Cache.Draw(Util.Cache.GetTexture("progressBar2").Text2D, World.WorldManager.BreathProgressBar2, Color.White);

                                    }
                                    else
                                    {
                                        //reset fields
                                        World.WorldManager.BreathProgressBar1 = new Rectangle(0, 0, 0, 0);
                                        World.WorldManager.BreathProgressBar2 = new Rectangle(0, 0, 0, 0);
                                        World.WorldManager.CurrentTimeElapsed = -1;
                                        World.WorldManager.BreathTimeElapsedSet = false;
                                        World.WorldManager.BreathProgressBarWidth = 10;
                                    }

                                    #endregion

                                 
                                    //draw markers to draw (in game, not on the map)
                                    Levels.LevelManager.CurrentMap.CurrentMapCell.DrawMarkersToDraw();


                                    //draw avatar
                                    #region AVATAR
                                    if (Util.Cache.Avatar.IsBeingHurt)
                                    {
                                        Util.Cache.Avatar.DrawHurtingCharacter();
                                    }
                                    else
                                    {
                                        Util.Cache.Avatar.DrawCharacter();
                                    }
                                    ////draw avatar action menu
                                    //World.WorldManager.DrawAvatarActionMenu();


                                    #endregion

                                    //draw Inventory
                                    World.WorldManager.DrawInventory();

                                    //draw item usage-action related items
                                    #region draw item usage-action related items
                                    World.WorldManager.DrawThrowFieldOfReach();
                                    #endregion

                                    //draw HUD
                                    #region HUD
                                    World.WorldManager.DrawHUD();
                                    #endregion

                                   
                                }

                            }


                            //bomb
                            #region BOMB WIRES
                            //if avatar is defusing it,
                            //draw wires
                            if (World.WorldManager.IsDefusingBomb)
                            {
                                if (!World.BombHandler.ShowingBombFailInformation)
                                {
                                    #region Draw WIRES
                                    //draw wire
                                   
                                        //see which bomb has been tapped on, to defuse
                                      
                                            //draw wires for that bomb
                                            World.BombHandler.PrepareDefusingWires();

                                            //draw wires
                                            for (int w = 0; w < World.WorldManager.BombInstanceBeingDefused.Wires.Count; w++)
                                            {

                                                //if grace period is  -1, then draw defusing wire first
                                                //if grace period is not -1, then defusing wire drawn, draw rest of the wires after some time
                                                if (!World.WorldManager.WiresShown)
                                                {
                                                    if (World.WorldManager.BombInstanceBeingDefused.Wires[w].DefusingWire)
                                                    {
                                                        //draw defusing wire
                                                        World.BombHandler.DrawWires(World.WorldManager.BombInstanceBeingDefused.Wires[w]);

                                                        //save current elapsed time (only if not saved yet)
                                                        if (World.WorldManager.ElapsedDefusingWireGracePeriod == -1)
                                                        {
                                                            World.WorldManager.ElapsedDefusingWireGracePeriod = Util.Cache.GameTime.TotalGameTime.TotalMilliseconds;
                                                        }

                                                        //check if it's time to show rest of the wires (not defusing ones)
                                                        if (Util.Cache.GameTime.TotalGameTime.TotalMilliseconds - World.WorldManager.ElapsedDefusingWireGracePeriod > World.WorldManager.BombInstanceBeingDefused.DefusingWireGracePeriod)
                                                        {
                                                            World.WorldManager.WiresShown = true;
                                                        }


                                                        break;
                                                    }
                                                }
                                                else
                                                {
                                                    //draw, only if defusing wire grace period has elapsed
                                                    World.BombHandler.DrawWires(World.WorldManager.BombInstanceBeingDefused.Wires[w]);
                                                    World.WorldManager.WiresShown = true;



                                                    //set all wires drawn, if the last wire has been just drawn
                                                    if (!World.BombHandler.StartShuffle) //if not started shuffling yet
                                                    {
                                                        if (w == World.WorldManager.BombInstanceBeingDefused.Wires.Count - 1)
                                                        {
                                                            World.BombHandler.StartShuffle = true; //all wires have been draw, start shuffling
                                                            //save current time elapsed
                                                            World.BombHandler.TimeElapsedSinceWiresDrawn = Util.Cache.GameTime.TotalGameTime.TotalMilliseconds;
                                                        }
                                                    }

                                                }


                                            }



                                        
                                    
                                    #endregion
                                }

                                //draw all elements of the bomb listed below 
                                    //draw bomb heat
                                    if (World.BombHandler.DrawBombHeat)
                                    {
                                        World.BombHandler.DrawBombDefusingHeat();
                                    }

                                    //draw defusing result
                                    if (World.BombHandler.BombFail)
                                    {
                                        World.BombHandler.DrawBombFailed();
                                    }

                                    if (World.BombHandler.BombPass)
                                    {
                                        World.BombHandler.DrawBombPass();
                                    }
                                
                            }


                            #endregion

                            //Util.Cache.GetFont("default").DrawString(World.WorldManager.accReading.X + "/" + World.WorldManager.accReading.Y + "/" + World.WorldManager.accReading.Z, new Vector2(0, 15), 0, Color.Red);
                            //draw current tap position (X/Y)
                            //_DebugOutput = "WORK IN PROGRESS (missing a few features,art,music,QA&bugfixing)";
                            //Util.Cache.GetFont("default").DrawString(tapPos.X + "/" + tapPos.Y, new Vector2(0, 15), 0, Color.Red);
                            //Util.Cache.GetFont("default").DrawString(_DebugOutput, new Vector2(120, 15), 0, Color.Red);
                            
                           

                            //draw flying points when adding points
                            if (World.WorldManager.AwardingAnimationOn)
                            {
                                if (!World.WorldManager.SlidingInInformation)
                                {
                                    World.WorldManager.DrawAwardingPoints();
                                }
                                else
                                {
                                    //draw sliding in info
                                    World.WorldManager.DrawSlidingInInfo();
                                }
                            }

                            #region DRAW DEBUG INFO-NODES FOR PATH FOLLWING

                            //World.PathFinding.DrawNodes();


                            #endregion

                            #region DRAW MESSAGE BOX

                            Util.MessageBox.Draw();

                            #endregion


                            break;

                           

                            #endregion


                        }
                    case Util.Cache.Screen.SplashScreen1:
                        {
                            #region splash screen

                            Screens.SplashScreen1.Draw();

                            #endregion

                            break;
                        }
                    case Util.Cache.Screen.MapSelector:
                        {
                            #region draw map selector


                            Screens.MapSelector.Draw();




                            #endregion
                            break;


                        }
                    case Util.Cache.Screen.LevelSelector:
                        {
                            #region draw level selector

                            Screens.LevelSelector.Draw();

                            #endregion

                            break;
                        }
                    case Util.Cache.Screen.Menu:
                        {
                            #region draw the main menu
                            GraphicsDevice.Clear(Color.White);

                            Screens.MainMenu.DrawMainMenu();

                            //draw current tap position (X/Y)
                            //Util.Cache.GetFont("default").DrawString(tapPos.X + "/" + tapPos.Y, new Vector2(0, 15), 0, Color.Red);

                            

                            if (World.WorldManager.EverythingLoaded)
                            {
                                Util.Cache.GetFont("default").DrawString("CONTENT LOADED", new Vector2(0, 40), 0, Color.Red);
                            }

                            break;

                            #endregion
                        }
                    case Util.Cache.Screen.Error:
                        {

                            #region draw the error popup
                            //draw error popup
                            GraphicsDevice.Clear(Color.Purple);
                            Util.ErrorLogging.ShowError();


                            break;

                            #endregion
                        }
                    case Util.Cache.Screen.Options:
                        {

                            #region options secreen

                            GraphicsDevice.Clear(Color.Green);

                            break;

                            #endregion
                        }
                    case Util.Cache.Screen.GameOver:
                        {
                            #region game over

                            GraphicsDevice.Clear(Color.Black);
                            Util.Cache.Draw(Util.Cache.GetTexture("gameOver").Text2D, new Rectangle(0, 0, this.GraphicsDevice.Viewport.Width, this.GraphicsDevice.Viewport.Height), Color.White);


                            #endregion

                            break;

                        }
                    case Util.Cache.Screen.Pause:
                        {
                            #region pause screen

                            GraphicsDevice.Clear(Color.Black);
                            Screens.Pause.Draw();

                            Util.Cache.GetFont("default").DrawString(tapPos.X + "/" + tapPos.Y, new Vector2(0, 15), 0, Color.Red);
                            #endregion

                            break;
                        }
                    case Util.Cache.Screen.LoadMap:
                        {
                            #region loading map

                            GraphicsDevice.Clear(Color.Black);
                            Screens.LoadingMap.Draw();


                            #endregion

                            break;
                        }
                    case Util.Cache.Screen.Store:
                        {
                            #region store
                            GraphicsDevice.Clear(Color.Black);
                            Screens.Store.Draw();

                            Util.Cache.GetFont("default").DrawString(tapPos.X + "/" + tapPos.Y, new Vector2(0, 15), 0, Color.Red);

                            #endregion

                            break;
                        }


                }

                //draw build number
                Util.Cache.GetFont("small").DrawString(GetVersionNumber()+" FPS:"+_Fps.ToString(), new Vector2(0, this.GraphicsDevice.Viewport.Height - 15), 0, Color.Red);
               // Util.Cache.GetFont("small").DrawString("WORK IN PROGRESS", new Vector2(0, this.GraphicsDevice.Viewport.Height - 15), 0, Color.LightBlue);


                spriteBatch.End();
                base.Draw(gameTime);

            }
            catch (Exception ex)
            {
                Util.ErrorLogging.LogError(ex);
                return;
            }
        }
        
    }
}
